<template>
  <div>
    <el-table :data="tableData" border style="width: 100%" v-if="showTable">
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="120"></el-table-column>
      <el-table-column
        prop="address"
        label="地址"
        width="300"
      ></el-table-column>
    </el-table>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  data () {
    return {
      showTable: true,
      tableData: [
        { name: '张三', age: 20, address: '北京' },
        { name: '李四', age: 22, address: '上海' },
        { name: '王五', age: 25, address: '广州' }
      ]
    }
  },
  updated () {
    const tbody = document.querySelector('.el-table__body-wrapper tbody')
    if (tbody) {
      Sortable.create(tbody, {
        onEnd: (evt) => {
          this.showTable = false
          const oldIndex = evt.oldIndex
          const newIndex = evt.newIndex
          const x1 = JSON.parse(JSON.stringify(this.tableData[oldIndex]))
          const x2 = JSON.parse(JSON.stringify(this.tableData[newIndex]))

          this.$nextTick((_) => {
            this.showTable = true
            this.$set(this.tableData, newIndex, x1)
            this.$set(this.tableData, oldIndex, x2)
            console.log(this.tableData)
          })
        }
      })
    }
  },
  mounted () {
    const tbody = document.querySelector('.el-table__body-wrapper tbody')
    if (tbody) {
      Sortable.create(tbody, {
        onEnd: (evt) => {
          this.showTable = false
          const oldIndex = evt.oldIndex
          const newIndex = evt.newIndex
          const x1 = JSON.parse(JSON.stringify(this.tableData[oldIndex]))
          const x2 = JSON.parse(JSON.stringify(this.tableData[newIndex]))

          this.$nextTick((_) => {
            this.showTable = true
            this.$set(this.tableData, newIndex, x1)
            this.$set(this.tableData, oldIndex, x2)
            console.log(this.tableData)
          })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
